package com.imooc.miaosha.myredis;

import com.alibaba.fastjson.JSON;
import com.imooc.miaosha.util.BeanUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import redis.clients.jedis.Jedis;

/**
 * 自定义一个redis
 */
@Service
public class MyRedisService {
    @Autowired
    Jedis jedis;
    public <T> T get(KeyPrefix prefix, String key, Class<T> clazz){
        try{
            key=prefix.getPrefix()+key;
            String value=jedis.get(key);
            return BeanUtil.stringToBean(value,clazz);
        }finally {
            returnToPool(jedis);
        }
    }
    public <T> String set(KeyPrefix prefix,String key, T valueObj){
        try{
            key=prefix.getPrefix()+key;
            String valueStr= BeanUtil.beanToString(valueObj);
            return jedis.set(key,valueStr);
        }finally {
            returnToPool(jedis);
        }
    }


    private void returnToPool(Jedis jedis){
        if (jedis!=null) jedis.close();
    }
}
